package org.example.managere.controller.feibiao;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmKnowledgeFailureDto;
import org.example.managere.dto.feibiao.AmKnowledgeBasicDto;
import org.example.managere.service.feibiao.AmKnowledgeFailureService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 电机故障信息控制器 - 电机向量知识库 (极简版)
 */
@RestController
@RequestMapping("/api/feibiao/knowledge/failure")
@RequiredArgsConstructor
public class AmKnowledgeFailureController {
    
    private final AmKnowledgeFailureService failureService;
    
    /**
     * 创建故障记录
     */
    @PostMapping
    public ResponseEntity<AmKnowledgeFailureDto> createFailure(@Valid @RequestBody AmKnowledgeFailureDto dto) {
        AmKnowledgeFailureDto created = failureService.save(dto);
        return new ResponseEntity<>(created, HttpStatus.CREATED);
    }
    
    /**
     * 获取故障记录详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<AmKnowledgeFailureDto> getFailureById(@PathVariable Integer id) {
        Optional<AmKnowledgeFailureDto> failureOpt = failureService.findById(id);
        return failureOpt.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 更新故障记录
     */
    @PutMapping("/{id}")
    public ResponseEntity<AmKnowledgeFailureDto> updateFailure(@PathVariable Integer id, 
                                                             @Valid @RequestBody AmKnowledgeFailureDto dto) {
        if (!id.equals(dto.getId())) {
            return ResponseEntity.badRequest().build();
        }
        
        AmKnowledgeFailureDto updated = failureService.update(dto);
        return ResponseEntity.ok(updated);
    }
    
    /**
     * 删除故障记录
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteFailure(@PathVariable Integer id) {
        failureService.deleteById(id);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * 分页获取所有故障记录
     */
    @GetMapping
    public ResponseEntity<Page<AmKnowledgeFailureDto>> getAllFailures(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id,asc") String sort) {
        
        String[] sortParams = sort.split(",");
        Sort.Direction direction = sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc") 
                ? Sort.Direction.DESC : Sort.Direction.ASC;
        
        Pageable pageable = PageRequest.of(page, size, direction, sortParams[0]);
        Page<AmKnowledgeFailureDto> failures = failureService.findAll(pageable);
        
        return ResponseEntity.ok(failures);
    }
    
    /**
     * 根据关键字搜索故障记录
     */
    @GetMapping("/search")
    public ResponseEntity<Page<AmKnowledgeFailureDto>> searchFailures(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<AmKnowledgeFailureDto> failures = failureService.searchByKeyword(keyword, pageable);
        
        return ResponseEntity.ok(failures);
    }
    
    /**
     * 获取未修复的故障记录
     */
    @GetMapping("/unrepaired")
    public ResponseEntity<List<AmKnowledgeFailureDto>> getUnrepairedFailures() {
        List<AmKnowledgeFailureDto> failures = failureService.findUnrepairedFailures();
        return ResponseEntity.ok(failures);
    }
    
    /**
     * 根据电机ID查询故障记录
     */
    @GetMapping("/motor/{motorId}")
    public ResponseEntity<List<AmKnowledgeFailureDto>> getFailuresByMotorId(@PathVariable String motorId) {
        List<AmKnowledgeFailureDto> failures = failureService.findByMotorId(motorId);
        return ResponseEntity.ok(failures);
    }
    
    /**
     * 查询基本故障统计信息（极简版）
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getFailureStatistics() {
        // 获取所有故障记录
        List<AmKnowledgeFailureDto> allFailures = failureService.findAll();
        
        // 创建统计数据的Map
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalFailures", allFailures.size());
        statistics.put("unrepairedFailures", failureService.countUnrepairedFailures());
        statistics.put("averageRepairTime", failureService.findAverageRepairEfficiency() != null 
                ? failureService.findAverageRepairEfficiency() : 0);
        
        return ResponseEntity.ok(statistics);
    }
    
    /**
     * 获取所有可用的电机列表
     */
    @GetMapping("/motors")
    public ResponseEntity<List<AmKnowledgeBasicDto>> getAllMotors() {
        // 获取所有电机基础信息，前端可以使用这些信息来选择关联电机
        List<AmKnowledgeBasicDto> motors = failureService.findAllMotors();
        return ResponseEntity.ok(motors);
    }
} 